package io.dy.utils;

import java.io.BufferedReader;
import java.io.FileReader;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.StringJoiner;
import java.util.concurrent.TimeUnit;

/**
 * @author dmj
 * @date 2024年03月01日 下午7:53
 */
public class CommonUtils {


    /**
     * 读取指定路径的文件
     * @param path
     * @return
     */
    public static String readFile(String path){
        ClassLoader classLoader = CommonUtils.class.getClassLoader();
        URL url = classLoader.getResource("");
        assert url != null;
        String prePath = url.getPath();
        prePath = prePath.substring(0, prePath.lastIndexOf("target/classes")) + "/";
        try {
            BufferedReader reader = new BufferedReader(new FileReader(prePath + path));
            StringBuilder stringBuilder = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line);
            }
            reader.close();
            return stringBuilder.toString();
        }catch (Exception ex){
            ex.printStackTrace();
            return null;
        }
    }


    /**
     * 指定休眠事件 毫秒
     * @param millis
     */
    public static void sleepMillis(long millis){
        try {
            TimeUnit.MILLISECONDS.sleep(millis);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * 指定休眠事件 毫秒
     * @param seconds
     */
    public static void sleepSecond(long seconds){
        try {
            TimeUnit.SECONDS.sleep(seconds);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * 打印线程信息
     * @param msg
     */
    public static void printThreadLog(String msg){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //时间 ｜ 线程id | 线程名 ｜日志信息
        String result = new StringJoiner(" | ")
                .add(sdf.format(new Date()))
                .add(String.format("%2d", Thread.currentThread().getId()))
                .add(Thread.currentThread().getName())
                .add(msg).toString();
        System.out.println(result);
    }




    public static void main(String[] args) {
        String readFile = CommonUtils.readFile("dy.txt");
        CommonUtils.printThreadLog(readFile);
    }
}
